package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

import static com.sky.constant.MessageConstant.PASSWORD_EDIT_FAILED;
import static com.sky.constant.PasswordConstant.DEFAULT_PASSWORD;
import static com.sky.constant.StatusConstant.DISABLE;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     */
    public void add(EmployeeDTO employeeDTO) {
        //创建员工对象
        Employee employee = new Employee();
        //给员工对象赋值（状态，密码为默认值）
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setStatus(DISABLE);
        employee.setPassword(DigestUtils.md5DigestAsHex(DEFAULT_PASSWORD.getBytes()));
/*        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateTime(LocalDateTime.now());*/
        //调用mapper插入数据库
        employeeMapper.add(employee);
    }

    /**
     * 分页查询
     */
    public PageResult page(EmployeePageQueryDTO dto) {
        //开启分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //调用mapper查询
        Page<Employee> list = employeeMapper.page(dto);
        //封装PageResult对象返回
        return new PageResult(list.getTotal(), list.getResult());
    }


    /**
     * 启用、禁用员工账号
     */
    public void startOrStop(Integer status, Long id) {
        //将status和id封装成员工对象，调用mapper进行修改(修改人和最后修改时间)
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
/*                .updateUser(BaseContext.getCurrentId())
                .updateTime(LocalDateTime.now())*/
                .build();
        employeeMapper.update(employee);
    }


    /**
     * 根据id查询员工(查询回显)
     */
    public Employee getById(Long id) {
        //根据id查询员工数据
        Employee employee = employeeMapper.getById(id);
        return employee;
    }


    /**
     * 修改员工信息
     */
    public void update(EmployeeDTO employeeDTO) {
        //创建Employee对象
        Employee employee = new Employee();
        //给Employee对象赋值 将employeeDTO中的值copy到Employee中
        BeanUtils.copyProperties(employeeDTO,employee);
        //更改修改人和最后修改时间
/*        employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setUpdateTime(LocalDateTime.now());*/
        //调用mapper进行修改  (可以和启用、禁用员工账号复用一个mapper)
        employeeMapper.update(employee);
    }


    /**
     * 修改密码
     */
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        //拿到需要修改密码员工的id 根据id查询员工信息
        Employee employee = employeeMapper.getById(BaseContext.getCurrentId());
        //对前端传过来的密码进行加密
        String oldpassword = DigestUtils.md5DigestAsHex(
                passwordEditDTO.getOldPassword().getBytes());
        //判断前端传来密码和数据库中的密码是否一致
        if(!employee.getPassword().equals(oldpassword)){
            //不一致抛异常
            throw new PasswordErrorException(PASSWORD_EDIT_FAILED);
        }
        //一致，调用mapper修改密码(加密 修改人和最后修改时间)
        employee.setPassword(DigestUtils.md5DigestAsHex(
                passwordEditDTO.getNewPassword().getBytes()));
/*        employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setUpdateTime(LocalDateTime.now());*/
        employeeMapper.update(employee);
    }
}
